<template>
  <div
    class="home"
    v-infinite-scroll="loadMoreVideo"
    :infinite-scroll-disabled="loadDisabled"
  >
    <div class="header">
      <GlobalHeader class="color-white"></GlobalHeader>
      <div class="header-logo">
        <img src="../assets/img/bilibili.png" alt="" />
      </div>
    </div>

    <div class="header-item-box p-[0px_60px] desktop:p-[0px_140px]">
      <div class="header-icon">
        <div>
          <span class="iconfont icon-dongtai"></span>
          <p>动态</p>
        </div>
        <div>
          <span class="iconfont icon-remen"></span>
          <p>热门</p>
        </div>
      </div>
      <div class="header-item">
        <div class="header-item-left">
          <a href="#" v-for="contentCategory in contentCategoryList">{{
            contentCategory.categoryName
          }}</a>
        </div>
        <div class="header-item-right">
          <a href="#">
            <span class="iconfont icon-zhuanlan"></span>
            <span>专栏</span>
          </a>
          <a href="#">
            <span class="iconfont icon-huodong"></span>
            <span>活动</span>
          </a>
          <a href="#">
            <span class="iconfont icon-shequzhongxin"></span>
            <span>社区中心</span>
          </a>
          <a href="#">
            <span class="iconfont icon-zhibo"></span>
            <span>直播</span>
          </a>
          <a href="#">
            <span class="iconfont icon-ketang"></span>
            <span>课堂</span>
          </a>
          <a href="#">
            <span class="iconfont icon-xingerebang"></span>
            <span>新歌热榜</span>
          </a>
        </div>
      </div>
    </div>

    <GlobalHeader
      class="color-black position-fixed position-top-none w-full bg-white border-b border-b-solid border-b-zinc-1 z-50"
      v-if="scrollY >= 100"
    ></GlobalHeader>

    <div class="w-full p-[0px_60px] desktop:p-[0px_140px] box-border">
      <div class="grid grid-cols-5 gap-20px">
        <el-carousel
          class="col-span-2 row-span-2 bg-red"
          style="width: 100%; height: 359px"
          autoplay
        >
          <el-carousel-item style="width: 100%">
            <img src="../assets/img/home/lb-1-test.png" width="100%" />
          </el-carousel-item>
          <el-carousel-item style="width: 100%">
            <img src="../assets/img/home/lb-2-test.png" width="100%" />
          </el-carousel-item>
        </el-carousel>

        <div
          v-for="(video, index) in videoList"
          :key="index"
          class="cursor-pointer"
          @click="router.push({ path: `/video/${video.id}` })"
        >
          <div
            @mouseenter="playVideo(index)"
            @mouseleave="pauseVideo(index)"
            class="flex justify-center aspect-video relative"
          >
            <!-- 视频（默认隐藏，悬停时播放） -->
            <video
              class="w-full b-rd-4px object-contain bg-#000 ___"
              ref="videoPlayers"
              preload="none"
              loop
              muted
              :poster="video.coverUrl"
            >
              <source :src="video.fileUrl" type="video/mp4" />
              <source :src="video.fileUrl" type="video/webm" />
            </video>
            <div
              v-show="!isPlaying[index]"
              class="absolute bottom-0 c-white flex justify-between w-full p-x-10px p-b-5px box-border text-13px"
            >
              <div>
                <span class="iconfont icon-shipin v-bottom"></span>
                {{ video.playCount }}
                <span class="iconfont icon-danmushu m-l-10px v-bottom"></span>
                {{ video.danmakuCount }}
              </div>
              <span>{{
                DateUtil.convertSecondsToHMS(Number(video.duration).toFixed(0))
              }}</span>
            </div>
          </div>
          <p class="line-clamp-2 c-#18191c text-15px m-y-10px h-40px">
            {{ video.title }}
          </p>
          <div class="c-#9499a0 text-13px">
            <span class="iconfont icon-upzhu v-mid"></span>
            {{ video.createByName }}
            {{ DateUtil.formatDateToShort(video.createTime) }}
          </div>
        </div>

        <!-- 交互体验 -->
        <el-skeleton v-if="loading" v-for=" in 6" animated>
          <template #template>
            <div>
              <el-skeleton-item
                variant="image"
                style="
                  width: 100%;
                  aspect-ratio: 16 / 9;
                  height: auto;
                  padding-bottom: 10px;
                  border-radius: 4px;
                "
              />
              <el-skeleton :rows="2" />
            </div>
          </template>
        </el-skeleton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onBeforeUnmount, onMounted, ref } from "vue";
import { listContentCategory as listContentCategoryApi } from "@/api/contentCategory";
import type { ContentCategoryVO } from "@/api/contentCategory/types";
import GlobalHeader from "@/components/GlobalHeader.vue";
import { listVideo as listVideoApi } from "@/api/video";
import type { VideoVO } from "@/api/video/types";
import { DateUtil } from "@/utils/dateUtil";
import router from "@/router";

const contentCategoryList = ref<ContentCategoryVO[]>([]); // 内容分类列表
const scrollY = ref(0); // 用于存储滚动位置
const queryParams = ref<PageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const videoList = ref<VideoVO[]>([]); // 视频数据
const videoPlayers = ref([]); //视频对象ref
const isPlaying = ref([]); // 是否播放

const loading = ref(false); // 骨架是否加载中
const loadDisabled = ref(false); // 是否禁用无限滚动加载
const hasFirstLoad = ref(false);

// 鼠标移入视频
const playVideo = async (index) => {
  const video = videoPlayers.value[index];
  if (video) {
    isPlaying.value[index] = true;
    try {
      await video.play();
    } catch (err) {
      console.log("播放被阻止:", err);
    }
  }
};

// 鼠标移出视频
const pauseVideo = async (index) => {
  const video = videoPlayers.value[index];
  if (video) {
    isPlaying.value[index] = false;
    await video.pause();
    // video.currentTime = 0; // 重置播放进度
  }
};

// 获取视频列表
const getVideo = async () => {
  loading.value = true;

  const res = await listVideoApi(queryParams.value);
  if (res.rows) {
    videoList.value.push(...res.rows);
    isPlaying.value.push(...videoList.value.map(() => false));
  }
  loading.value = false;

  return res.rows;
};

// 加载更多视频
const loadMoreVideo = async () => {
  if (loading.value || loadDisabled.value) return;

  // 首次 load，只让 v-infinite-scroll 触发一次
  if (!hasFirstLoad.value) {
    hasFirstLoad.value = true;
  } else {
    queryParams.value.pageNum += 1;
  }
  // queryParams.value.pageNum = queryParams.value.pageNum + 1;
  const rows = await getVideo();
  if (!rows?.length) {
    queryParams.value.pageNum = Math.max(1, queryParams.value.pageNum - 1);
    loadDisabled.value = true; // 没有更多数据了，禁用无限滚动加载
  }
};

const onScroll = () => (scrollY.value = window.scrollY);

onBeforeMount(async () => {
  // 监听滚动条
  window.addEventListener("scroll", onScroll);
});

onMounted(async () => {
  const res = await listContentCategoryApi();
  contentCategoryList.value = res.rows;
});

onBeforeUnmount(() => {
  // 卸载滚动条事件
  window.removeEventListener("scroll", onScroll);
});
</script>

<style lang="less" scoped>
@import "../assets/styles/index.less";
</style>
